package com.xxxx.oa.web.action;

import com.xxxx.oa.utils.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet({"/user/login","/user/logout"})
public class UserServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String servletPath = request.getServletPath();
        if("/user/logout".equals(servletPath)){
            doLogout(request,response);
        }else if("/user/login".equals(servletPath)){
            doLogin(request,response);
        }
    }
    protected void doLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if(session!=null){
            session.invalidate();
            response.sendRedirect(request.getContextPath());
        }
    }

    protected void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String loginName = request.getParameter("loginName");
        String loginPwd = request.getParameter("loginPwd");
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        boolean isflag=false;
        try {
            conn = DBUtil.getConnection();
            String sql="select * from t_user where loginName = ? and loginPwd = ?";
            ps=conn.prepareStatement(sql);
            ps.setString(1,loginName);
            ps.setString(2,loginPwd);
            rs=ps.executeQuery();
            if(rs.next()){
                isflag=true;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(conn,ps,rs);
        }
        if(isflag){
            HttpSession session = request.getSession();
            session.setAttribute("loginName",loginName);

            String f = request.getParameter("f");
            if("1".equals(f)){
                Cookie cookie1 = new Cookie("loginName",loginName);
                Cookie cookie2 = new Cookie("loginPwd",loginPwd);
                cookie1.setMaxAge(60*60*24*10);
                cookie2.setMaxAge(60*60*24*10);
                cookie1.setPath(request.getContextPath());
                cookie2.setPath(request.getContextPath());
                response.addCookie(cookie1);
                response.addCookie(cookie2);
            }
            response.sendRedirect(request.getContextPath()+"/dept/list");
        }else{
            response.sendRedirect(request.getContextPath()+"/error.jsp");
        }


    }
}
